package cn.sylinx.hbatis.ext.function;

import cn.sylinx.hbatis.exception.FunctionException;
import cn.sylinx.hbatis.ext.parse.ValueTokenHandler;

public class FunctionParser {

	private ValueTokenHandler handler;

	public FunctionParser(ValueTokenHandler handler) {
		this.handler = handler;
	}

	public static final String TOKEN_FUN_BEGIN = "#FUNC[";
	public static final String TOKEN_FUN_END = "]";

	public String parse(String statement) {
		return parseDynamicSql(statement).toString();
	}

	private String parseDynamicSql(String st) {

		StringBuilder sb = new StringBuilder();
		parseSqlNext(st, sb);
		return sb.toString();
	}

	private void parseSqlNext(String st, StringBuilder sb) {

		if (st == null) {
			throw new RuntimeException("statment is null");
		}

		int is = st.indexOf(TOKEN_FUN_BEGIN);
		if (is == -1) {
			sb.append(st);
			return;
		}

		String tmp = st.substring(is);
		int is1 = tmp.indexOf(TOKEN_FUN_END);
		int ie = is1 + is;

		if (is1 == -1) {
			throw new RuntimeException("illegal function statement");
		}

		String split = st.substring(is + TOKEN_FUN_BEGIN.length(), ie);

		// 解析函数
		String dynamicSql = handFunction(split);

		String before = st.substring(0, is) + (dynamicSql == null ? "" : dynamicSql);
		sb.append(before);

		String after = st.substring(ie + TOKEN_FUN_END.length());
		parseSqlNext(after, sb);
	}

	private String handFunction(String split) {

		int index = split.indexOf(",");
		if (index == -1) {
			throw new FunctionException("函数参数错误");
		}
		String alias = split.substring(0, index);
		String input = split.substring(index + 1);
		IFunction af = FunctionFactory.get().getFunction(alias);
		return af.invoke(handler, input);
	}
}
